package utility;

import java.io.*;

public class ByteBufferOutputStream extends OutputStream {

   private byte[] buffer;
   private int length;
   private int pos = 0;
   
   public ByteBufferOutputStream(byte[] buffer) {
      this.buffer = buffer;
      this.length = buffer.length;
   }
   
   public ByteBufferOutputStream(byte[] buffer, int length) {
      this.buffer = buffer;
      this.length = length;
   }
   
   public byte[] getBuffer () {
      return this.buffer;
   }
   
   public int getSize () {
      return this.pos;
   }
   
   @Override
   public void write(int b) throws IOException {
      
      if (pos >= this.length) {
         throw new EOFException("End of stream reached.");
      }
      
      buffer[pos++] = (byte) b;
   }
   
   @Override
   public void write (byte[] buffer) throws IOException {
      this.write(buffer, 0, buffer.length);     
   }
   
   @Override
   public void write (byte[] buffer, int offset, int length) throws IOException {
      
      if (pos + length > this.length) {
         throw new EOFException("End of stream would be reached.");
      }
      
      System.arraycopy(buffer, offset, this.buffer, pos, length);
      pos += length;
      
   }
   
}
